import Taro, { Component, Config, getCurrentPages } from "@tarojs/taro";
import { View, Picker } from '@tarojs/components'
import { AtForm, AtInput, AtButton, AtSwitch, AtListItem } from "taro-ui";
import { observer, inject } from '@tarojs/mobx'
import Stores from '../../../../stores/storeIdentifier'
import OrderStore from "../../../../stores/orderStore"
import './index.scss'
import { UserShippingAddressInputDto } from "../../../../services/cart/dto/userShippingAddressInputDto"
import { AreaForCascaderModel } from "../../../../services/cart/dto/areaForCascaderModel"
import WxOpenStore from "src/stores/wxOpenStore";

export interface IIndexProps {
  orderStore: OrderStore
  wxOpenStore: WxOpenStore
}

@inject(Stores.OrderStore,Stores.WxOpenStore)
@observer
class Index extends Component<IIndexProps> {

  model: UserShippingAddressInputDto = new UserShippingAddressInputDto();
  districts: AreaForCascaderModel[][] = []
  areaCodeDisplayName: string = '省、市、城区'
  provinceName: string;
  cityName: string;
  districtName: string;
  selectArea: number[] = [0, 0, 0]
  selectAreaCode: AreaForCascaderModel[]
  areaParents: AreaForCascaderModel[];
  constructor(props: any) {
    super(props)
  }


  config: Config = {
    navigationBarTitleText: '编辑地址'
  };

  async componentWillMount() {
    this.selectArea = [0, 0, 0];
    if (this.$router.params.id) {
      await this.getAddress();
    }
    else {
      this.model = new UserShippingAddressInputDto();
      this.areaCodeDisplayName = '省、市、城区';
      this.model.areaCode = '11010100'
    }
    await this.getAreaAndParents()
  }

  async getAreaAndParents() {
    if (this.model.areaCode) {
      await this.props.orderStore.getAreaAndParents(this.model.areaCode);
      this.areaParents = this.props.orderStore.parentsAreas;
      this.selectAreaCode = []
      if (this.areaParents && this.areaParents.length) {
        this.areaParents.map((item, index) => {
          this.selectAreaCode.push(item)
        })
      }
    }
    this.setState({}, async () => {
      await this.getAreaParentsAndSiblings()
    })
  }

  async getAreaParentsAndSiblings() {
    await this.props.orderStore.getAreaParentsAndSiblings(this.model.areaCode)
    this.districts = this.props.orderStore.districts

    if (this.districts && this.districts.length) {
      this.districts.map((item, index) => {
        if (this.selectAreaCode && this.selectAreaCode.length)
          this.selectArea[index] = item.findIndex(m => m.value == this.selectAreaCode[index].value)
      })
    }
    this.setState({})
  }

  async getAddress() {
    await this.props.orderStore.getUserShippingAddress(this.$router.params.id);
    const { address } = this.props.orderStore;

    if (address) {
      this.model.address = address.address;
      this.model.areaCode = address.areaCode;
      this.model.isChecked = address.isChecked;
      this.model.isDefault = address.isDefault;
      this.model.mobilephone = address.mobilephone;
      this.model.receiptUserName = address.receiptUserName;
      this.model.telephone = address.telephone;
      this.model.userId = address.userId;
      this.model.zipCode = address.zipCode;
      this.areaCodeDisplayName = address.areaCodeDisplayName;
      this.model.id = address.id;
    }

    this.setState({})
  }


  onChange = async (e) => {
    if (this.provinceName) {
      this.areaCodeDisplayName = this.provinceName + ' ' + this.cityName + ' ' + this.districtName;
    }
    else {
      this.areaCodeDisplayName = this.districts[0][this.selectArea[0]].label + ' ' + this.districts[1][this.selectArea[1]].label + ' ' + this.districts[2][this.selectArea[2]].label;
    }
    this.model.areaCode = this.districts[2][this.selectArea[2]].value
    this.selectArea = [this.selectArea[0], this.selectArea[1], this.selectArea[2]]
    this.setState({});
  }

  onColumnchange = async e => {
    const { column, value } = e.detail
    //以下方法直接用内部循环不好使getAreas
    this.selectArea[column] = value
    if (column == 0) {
      await this.props.orderStore.getAreas(this.districts[0][value].value);
      this.districts[1] = this.props.orderStore.areas;

      if (this.districts[1][0]) {
        await this.props.orderStore.getAreas(this.districts[1][0].value);
        this.districts[2] = this.props.orderStore.areas;
      }
      this.provinceName = this.districts[0][value].label;
      if (this.districts[1][this.selectArea[1]])
        this.cityName = this.districts[1][this.selectArea[1]].label;
      else {
        this.cityName = this.districts[1][0].label;
      }
      if (this.districts[2][this.selectArea[2]])
        this.districtName = this.districts[2][this.selectArea[2]].label;
      else {
        this.districtName = this.districts[2][0].label;
      }
    }
    else if (column == 1) {
      await this.props.orderStore.getAreas(this.districts[1][value].value);
      this.districts[2] = this.props.orderStore.areas;
      this.setState({}, () => {
        this.cityName = this.districts[1][value].label;
        if (this.districts[2][this.selectArea[2]])
          this.districtName = this.districts[2][this.selectArea[2]].label;
        else {
          this.districtName = this.districts[2][0].label;
        }
      })

    }
    else if (column == 2) {
      this.districtName = this.districts[2][value].label;
    }

    this.setState({})
  }

  handleChangeReceiptUserName(value) {
    this.model.receiptUserName = value;
    this.setState({})
  }

  handleChangePhone(value) {
    this.model.mobilephone = value;
    this.setState({})
  }

  handleChangeAddress(value) {
    this.model.address = value;
    this.setState({})
  }

  handleChange(value) {
    this.model.isDefault = value;
    this.setState({})
  }

  async onSubmit(event) {
    await this.props.wxOpenStore.createFormIds([{ formId: event.detail.formId, formIdType: 0 }])
    if (!this.model.receiptUserName || this.model.receiptUserName === '') {
      Taro.showToast({
        title: '请输入收货人',
        icon: 'none',
      });
      return;
    }
    if (!/^1[2345789]\d{9}$/.test(this.model.mobilephone)) {
      Taro.showToast({
        title: '手机号格式不正确',
        icon: 'none',
      });
      return;
    }
    if (!this.model.areaCode || this.model.areaCode === '') {
      Taro.showToast({
        title: '请选择省市地区',
        icon: 'none',
      });
      return;
    }
    if (!this.model.address || this.model.address === '') {
      Taro.showToast({
        title: '请输入详细地址',
        icon: 'none',
      });
      return;
    }

    await this.props.orderStore.createOrUpdateUserShippingAddress(this.model);

    var pages = getCurrentPages()
    let fromPage = pages[pages.length - 2]
    fromPage.setData({
      editSuccess: true
    })
    Taro.navigateBack({
      delta: 1
    })
  }

  onReset(event) {
    this.model = new UserShippingAddressInputDto();
    this.model.areaCode = '';
    this.areaCodeDisplayName = '省、市、城区';
    this.setState({});
  }


  render() {
    return (
      <View>
        <AtForm
          reportSubmit={true}
          className='addr-form'
          onSubmit={this.onSubmit.bind(this)}
          onReset={this.onReset.bind(this)}
        >
          <AtInput
            name='receiptUserName'
            title=''
            type='text'
            placeholder='姓名'
            value={this.model.receiptUserName}
            onChange={this.handleChangeReceiptUserName.bind(this)}
          />
          <AtInput
            name='mobilephone'
            title=''
            type='text'
            placeholder='手机号码'
            value={this.model.mobilephone}
            onChange={this.handleChangePhone.bind(this)}
          />
          <Picker className="pick-cell" mode="multiSelector" rangeKey="label" range={this.districts}
            onColumnchange={this.onColumnchange.bind(this)}
            onChange={this.onChange}
            value={this.selectArea}>
            <AtListItem title={this.areaCodeDisplayName} extraText='(请选择地区)' />
          </Picker>
          <AtInput
            name='address'
            title=''
            type='text'
            placeholder='详细地址，如街道、楼盘号等'
            value={this.model.address}
            onChange={this.handleChangeAddress.bind(this)}
          />
          <AtSwitch title='设为默认' checked={this.model.isDefault} onChange={this.handleChange.bind(this)} />

          <View className='btn-wrap'>
            <AtButton formType='submit' type='primary'>提交</AtButton>
            <AtButton formType='reset'>重置</AtButton>
          </View>
        </AtForm>
      </View>
    )
  }
}

export default Index
